package org.leo.tree.handler;

import java.util.ArrayList;
import java.util.HashMap;

import org.leo.tree.beans.Tree;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TreeXMLHandler extends DefaultHandler {

	private ArrayList<Tree> treesList = new ArrayList<Tree>();
	private HashMap<String, String> addresses = new HashMap<String, String>();
	private Tree tree = null;
	private boolean streetTree = false;
	private boolean civicNumber = false;
	private boolean stdStreet = false;

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equalsIgnoreCase("StreetTree")) {
			streetTree = true;
			String treeID = attributes.getValue("TreeID");
			//System.out.println("Street tree Id : " + treeID);
			tree = new Tree();
			tree.setTreeId(treeID);
		}

		if (qName.equalsIgnoreCase("CivicNumber")) {
			civicNumber = true;
		}

		if (qName.equalsIgnoreCase("StdStreet")) {
			stdStreet = true;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String civicNum;
		String stdStr;
		if (civicNumber) {
			civicNum = new String(ch, start, length);
			tree.setCivicNumber(civicNum);
			//System.out.println("Civic Number : " + civicNum);
		}

		if (stdStreet) {
			stdStr = new String(ch, start, length);
			tree.setStdStreet(stdStr);
			//System.out.println("Std Street : " + stdStr);
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (streetTree) {
			streetTree = false;
			if(tree != null){
				String address = new StringBuffer(tree.getCivicNumber())
										.append(" ")
										.append(tree.getStdStreet())
										.append(" Canada").toString();
				if(!addresses.containsKey(address)){
					tree.setAddress(address);
					addresses.put(address, tree.getTreeId());
					treesList.add(tree);
				}
			}
		}

		if (civicNumber) {
			civicNumber = false;
		}

		if (stdStreet) {
			stdStreet = false;
		}
	}

	public ArrayList<Tree> getListOfTrees() {
		return treesList;
	}

}
